angular.module('baisonMessage', ['baisonDb', 'baisonService'])
//向服务器下载消息并更新下载状态到服务器

        .factory('messageGet', ['apiService', '$rootScope', '$q', 'dbReplace', 'timeStamp2String',
            function (apiService, $rootScope, $q, dbReplace, timeStamp2String) {
                return function () {
                    var url = 'sys/message/get_message';
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var user_code = $rootScope.user.UserCode;
                    var message_ids = [];
                    //从服务器下载数据
                    return apiService(url, {
                        shop_code: shop_code
                    }).then(function (ret) {
                        var deferred = $q.defer();
                        var promise = deferred.promise;
                        var count = 0;
                        //baison_app.api.alert({msg:ret,title:'ret'});
                        if(ret.data.status==1){
                            count = ret.data.data.length;
                        }
                        if (count > 0) {
                            deferred.resolve(ret.data.data);
                        } else {
                            deferred.reject(JSON.stringify($rootScope.language.TIP_MESSAGE_NEWS));
                        }
                        return promise;
                    }).then(function (data) {
                        var date_time = timeStamp2String(0, 'datetime');
                        var insert_data = [];
                        var deferred = {};
                    	var promise = {};
                        $.each(data, function (i, n) {
                        	deferred[i] = $q.defer();
                        	promise[i] = deferred[i].promise;
                            var _data = {
                                message_id: n.message_id,
                                title: n.title,
                                content: n.content,
                                start_time: n.start_time,
                                expiry_date: n.expiry_date,
                                end_time: n.end_time,
                                download_time: date_time
                            };
                            
                            insert_data.push(_data);
                            dbReplace('pos_message', insert_data, ['message_id'], ['expiry_date', 'title', 'content', 'start_time', 'end_time']).then(function(){
                            	deferred[i].resolve('success');
                            });
                            message_ids.push(n.message_id);
                        });
                        return promise;
                    }).then(function (success) {
                        var param = {};
                        param.shop_code = shop_code;
                        param.user_code = user_code;
                        var deferred = {};
                    	var promise = {};
                    	message_ids.forEach(function(e,i){
                    		deferred[i] = $q.defer();
                        	promise[i] = deferred[i].promise;
                    		param.message_id = e;
                    		apiService('sys/message/update_message', param).then(function(ret){
                                //baison_app.api.alert({msg:ret,title:'ret'});
                    			deferred[i].resolve('success');
                    		});
                    	});
                        return promise;
                    });
                };
            }])

//从下载的数据中读取信息
        .factory('messageRead', ['apiService', '$rootScope', '$q', 'dbSelect', 'timeStamp2String',
            function (apiService, $rootScope, $q, dbSelect, timeStamp2String) {
                return function () {
                    var datetime = timeStamp2String(0, 'datetime');
                    var user_code = $rootScope.user.UserCode;
                    var shop_code = $rootScope.current_shop.ShopCode;
                    //baison_app.api.alert({msg:shop_code,title:'shop_code'});
                    var sql = 'select p.* from pos_message p where (p.expiry_date = 0 or (p.expiry_date =1 and p.start_time < "' + datetime + '" and p.end_time > "' + datetime + '")) and p.message_id not in (select message_id from pos_message_read_user u  where  u.shop_code="' + shop_code + '" and u.user_code="'+user_code+'")';
                    //console.log(sql);
                    return dbSelect('YsPos', sql);
                };
            }])

//用户读取信息保存,并更新到服务器
        .factory('saveUserReadMessage', ['apiService', '$rootScope', '$q', 'dbReplace', 'timeStamp2String',
            function (apiService, $rootScope, $q, dbReplace, timeStamp2String) {
                var deferred = $q.defer();
                var promise = deferred.promise;
                return function (id) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var user_code = $rootScope.user.UserCode;
                    //更新读取消息用户 无网状态只更新本地
                    var connectionType = baison_app.api.connectionType;
                    //比如: wifi
                    if (connectionType != 'none') {
                        var param = {};
                        param.shop_code = shop_code;
                        param.message_id = id;
                        param.user_code = user_code;
                        return apiService('sys/message/update_user_read_message', param).then(function (ret) {
                            //API可用
                            var date_time = timeStamp2String(0, 'datetime');
                            if (ret.data.status == 1) {
                                var insert_data = {
                                    message_id: id,
                                    user_code: user_code,
                                    status: 1,
                                    read_time: date_time,
                                    shop_code:shop_code
                                };
                            } else {
                                var insert_data = {
                                    message_id: id,
                                    user_code: user_code,
                                    status: 0,
                                    read_time: date_time,
                                    shop_code: shop_code
                                };
                            }
                            var data = [];
                            data[0] = insert_data;
                            return dbReplace('pos_message_read_user', data, ['message_id', 'shop_code'], ['read_time', 'status','user_code']);
                        }, function (err) {
                            //API接口不可用
                            var date_time = timeStamp2String(0, 'datetime');
                            var insert_data = {
                                message_id: id,
                                user_code: user_code,
                                status: 0,
                                read_time: date_time,
                                shop_code: shop_code
                            };
                            var data = [];
                            data[0] = insert_data;
                            return dbReplace('pos_message_read_user', data, ['message_id', 'shop_code'], ['read_time', 'status','user_code']);
                        });
                    } else {
                        //没有网络就更新本地
                        var date_time = timeStamp2String(0, 'datetime');
                        var insert_data = {
                            message_id: id,
                            user_code: user_code,
                            status: 0,
                            read_time: date_time,
                            shop_code: shop_code
                        };
                        var data = [];
                        data[0] = insert_data;
                        return dbReplace('pos_message_read_user', data, ['message_id', 'shop_code'], ['read_time','user_code']);
                    }
                    //return promise;
                };
            }])

//从本地获取消息列表数据（历史消息）
        .factory('messageHistory', ['apiService', '$rootScope', '$q', 'dbSelect', 'timeStamp2String',
            function (apiService, $rootScope, $q, dbSelect, timeStamp2String) {
                return function () {
                    var user_code = $rootScope.user.UserCode;
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var sql = 'select p.*,u.status,u.read_time from pos_message_read_user u left join pos_message p on p.message_id = u.message_id where u.shop_code="' + shop_code + '" order by u.message_id asc ';
                    return dbSelect('YsPos', sql);
                };
            }]);

